// miniprogram/pages/home/home.js
Page({
  // 页面的初始数据
  data: {
    page: 0,
    ismore: true,
    complete: true,
    showModa: false,
    type: 0,
    goods: [],
    detail: {
      title: '',
      desc: '',
      nowPrice: '',
      oldPrice: '',
      archived: 0,
      sales: 0,
      picUrl: '',
      index: null
    }
  },
  // 加载数据
  getGoods() {
    if (!this.data.complete) return false
    if (!this.data.ismore) return wx.stopPullDownRefresh()
    this.setData({complete: false})
    wx.cloud.callFunction({
      name: 'goods',
      data: {
        page: this.data.page
      }
    })
    .then(({result}) => {
      const {data} = result
      // 数据不够后面没有数据
      if (data && data.length < 10) {
        this.setData({
          ismore: false,
          complete: true,
          goods: this.data.goods.concat(data)
        })
      }else {
        // 正常有数据
        this.setData({
          ismore: true,
          goods: this.data.goods.concat(data),
          complete: true,
          page: this.data.page + 1
        })
      }
      wx.stopPullDownRefresh()
    })
    .catch(() => {
      this.setData({complete: true})
      wx.stopPullDownRefresh()
    })
  },
  // 修改信息
  editer(e) {
    let _type = e.currentTarget.dataset.type | 0
    let _item = e.currentTarget.dataset.item
    let _index = e.currentTarget.dataset.index
    if (_type) {
      this.setData({
        type: _type,
        detail: {
          ..._item,
          index: _index
        },
        showModa: true
      })
    }else {
      this.setData({type: _type,showModa: true})
    }
  },
  // 选择图片
  upload() {
    const _this = this
    wx.chooseImage({
      count: 1,
      success(e) {
        const {errMsg, tempFilePaths} = e
        _this.setData({
          detail: {
            ..._this.data.detail,
            picUrl: tempFilePaths[0]
          }
        }) 
      }
    })
  },
  // 显示隐藏
  hideModa(e) {
    this.setData({
      showModa: false,
      type: 0,
      detail: {
        title: '',
        desc: '',
        nowPrice: '',
        oldPrice: '',
        archived: 0,
        sales: 0,
        picUrl: '',
        index: null
      }
    })
  },
  // 确认修改新增
  confirm() {
    const _this = this
    const detail = this.data.detail
    const {desc, nowPrice, oldPrice, picUrl, title, index} = detail
    if (!title) return wx.showModal({title: "请输入标题",showCancel: false})
    if (!/^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/.test(nowPrice)) return wx.showModal({title: "请输入合法价格，最多两位小数",showCancel: false})
    if (!/^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/.test(oldPrice)) return wx.showModal({title: "请输入合法折扣价格，最多两位小数",showCancel: false})
    if (!desc) return wx.showModal({title: "请输入描述",showCancel: false})
    if (!picUrl) return wx.showModal({title: "请选择预览图",showCancel: false})
    wx.showLoading({
      title: '加载中...',
      mask: true,
    })
    // 判断图片是否为临时路径，为临时路径需要先上传
    if (~picUrl.indexOf('http://tmp/')) {
      // 获取图片信息
      wx.getImageInfo({
        src: detail.picUrl,
        success ({type, path}) {
          // 图片上传
          wx.cloud.uploadFile({
            filePath: path,
            cloudPath: `${Date.parse(new Date) +  Math.floor(Math.random() * (1000000000 - 1 + 1)) + 1}.${type}`
          })
          .then(({fileID}) => {
            wx.cloud.callFunction({
              name: 'upload',
              data: {
                detail: {
                  ...detail,
                  picUrl: fileID
                }
              }
            })
            .then((res) => {
              // 判断是否为修改
              if (index != null) {
                let _g = _this.data.goods
                _g[index] = detail
                _this.setData({
                  goods: _g
                })
                wx.hideLoading()
                _this.hideModa()
              }else {
                wx.hideLoading()
                _this.hideModa()
                _this.setData({
                  goods: [],
                  page: 0,
                  ismore: true
                })
                _this.getGoods()
              }
            })
          })
          .catch(() => {
            wx.hideLoading()
            wx.showModal({
              title: "操作失败，请稍后再试",
              showCancel: false
            })
          })
        },
        fail() {
          wx.hideLoading()
          wx.showModal({
            title: "操作失败，请稍后再试",
            showCancel: false
          })
        }
      })
    }else {
      wx.cloud.callFunction({
        name: 'upload',
        data: {
          detail: {
            ...detail
          }
        }
      })
      .then((res) => {
        let _g = _this.data.goods
        _g[index] = detail
        _this.setData({
          goods: _g
        })
        wx.hideLoading()
        _this.hideModa()
      })
    }
  },
  // 属性修改
  bindinput(e) {
    const _this = this
    const {value} = e.detail
    const {key} = e.currentTarget.dataset
    let detail = _this.data.detail
    let timer = null
    detail[key] = value
    // if (key == 'nowPrice' || key == 'oldPrice') detail[key] = value ? parseFloat(value).toFixed(2) : 0
    clearTimeout(timer)
    timer = setTimeout(() => {
      _this.setData({
        detail
      })
      clearTimeout(timer)
    }, 300);
  },
  // 生命周期函数--监听页面加载
  onLoad: function (options) {
    wx.startPullDownRefresh()
  },
  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh: function () {
    this.setData({
      goods: [],
      page: 0,
      ismore: true
    })
    this.getGoods()
  },
  // 页面上拉触底事件的处理函数
  onReachBottom: function () {
    this.getGoods()
  },
  // 用户点击右上角分享
  onShareAppMessage: function () {

  }
})